home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / c / mc302emb.zip / PTR2FUNC.C < prev    next >
C/C++ Source or Header  |  1994-03-18  |  2KB  |  52 lines

  1. /*
  2.  * Example program demonstrating calling functions indirectly through
  3.  * a table of pointers.
  4.  *
  5.  * Although MICRO-C does not have a pointer-to-function data type, it does
  6.  * allow you to call indirectly through any other type of pointer, thereby
  7.  * providing the functionality of pointers-to-functions.
  8.  */
  9.  
  10. #include cflea.h
  11.  
  12. /* DEMO functions to place in table (defined BEFORE table) */
  13. char *func0() {    return "Zero";  }
  14. char *func1() {    return "One";   }
  15. char *func2() { return "Two";   }
  16. char *func3() { return "Three"; }
  17. char *func4() { return "Four";  }
  18. char *func5() { return "Five";  }
  19. char *func6() { return "Six";   }
  20. char *func7() { return "Seven"; }
  21. char *func8() { return "Eight"; }
  22. char *func9() { return "Nine";  }
  23.  
  24. /*
  25. Note that in order to initialize a variable with the address of
  26. a symbol, that symbol must be already defined. If you wish to
  27. use functions (or variables) which are defined further down in
  28. the source file, you can use "extern" to define and prototype
  29. the symbol in advance.
  30. */
  31. extern char *func10();
  32.  
  33. /*
  34. Table of pointers to functions. Note that one level of indirection
  35. is used to access the function. Therefore, if we want functions which
  36. return pointers-to-char (char *), we have to declare the table as
  37. pointers-to-pointers-to-char (char **)
  38. */
  39. char **func_table[] = { &func0, &func1, &func2, &func3,
  40.     &func4, &func5, &func6, &func7, &func8, &func9, &func10 };
  41.  
  42. /* Simple program to loop, calling each function from table */
  43. main()
  44. {
  45.     int i;
  46.     for(i=0; i < sizeof(func_table)/sizeof(char **); ++i)
  47.         printf("func%u() = '%s'\n", i, (*func_table[i])() );
  48. }
  49.  
  50. /* Example of function defined AFTER table */
  51. char *func10() { return "Last function in table"; }
  52.